/**
 * 
 */
package com.teamall.web.app.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.teamall.core.common.Page;
import com.teamall.framework.exception.BaseAppException;
import com.teamall.framework.log.LogManager;
import com.teamall.framework.util.Utils;
import com.teamall.web.app.common.ResultFactory;
import com.teamall.web.app.vo.AppFamilyAidLogVO;
import com.teamall.web.app.vo.AppFamilyIncomeVO;
import com.teamall.web.app.vo.AppFamilyInfoPO;
import com.teamall.web.app.vo.AppFamilyInfoVO;
import com.teamall.web.app.vo.AppFamilyMemberVO;
import com.teamall.web.app.vo.AppFamilyVistedLogVO;
import com.teamall.web.base.vo.ResResult;
import com.teamall.web.family.db.po.FamilyAidLogPO;
import com.teamall.web.family.db.po.FamilyIncomePO;
import com.teamall.web.family.db.po.FamilyInfoPO;
import com.teamall.web.family.db.po.FamilyMemberPO;
import com.teamall.web.family.db.po.FamilyVisitedLogPO;
import com.teamall.web.family.service.IFamilyAidLogService;
import com.teamall.web.family.service.IFamilyIncomeService;
import com.teamall.web.family.service.IFamilyInfoService;
import com.teamall.web.family.service.IFamilyMemberService;
import com.teamall.web.family.service.IFamilyVisitedLogService;
import com.teamall.web.fpgz.db.po.CodeFamilyAidLogPO;
import com.teamall.web.fpgz.db.po.CodeFamilyIncomePO;
import com.teamall.web.fpgz.db.po.CodeFamilyInfoPO;
import com.teamall.web.fpgz.db.po.CodeFamilyMemberPO;
import com.teamall.web.fpgz.db.po.CodeFamilyVistedLogPO;
import com.teamall.web.fpgz.service.ICodeFamilyAidLogService;
import com.teamall.web.fpgz.service.ICodeFamilyIncomeService;
import com.teamall.web.fpgz.service.ICodeFamilyInfoService;
import com.teamall.web.fpgz.service.ICodeFamilyMemberService;
import com.teamall.web.fpgz.service.ICodeFamilyVistedLogService;
import com.teamall.web.sys.db.po.SysUserPO;
import com.teamall.web.sys.service.ISysUserService;

/**
 * <Description>贫困户相关接口 <br>
 * 
 * @author pan.xiaobo<br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2017年8月2日 <br>
 * @since V1.0<br>
 * @see com.teamall.web.app.controller <br>
 */
@Controller
@RequestMapping("/app/family")
public class AppFamilyController {

    private static final LogManager logger = LogManager
            .getLogger(AppFamilyController.class);

    // 家庭信息
    @Autowired
    private ICodeFamilyInfoService codeFamilyInfoService;

    // 家庭成员
    @Autowired
    private ICodeFamilyMemberService codeFamilyMemberService;

    // 走访日志
    @Autowired
    private ICodeFamilyVistedLogService codeFamilyVistedLogService;

    // 帮扶记录
    @Autowired
    private ICodeFamilyAidLogService codeFamilyAidLogService;

    // 家庭收入
    @Autowired
    private ICodeFamilyIncomeService codeFamilyIncomeService;

    // 3.3.6. 填写走访日志
    @Autowired
    private IFamilyVisitedLogService familyVisitedLogService;

    // 3.3.7. 填写帮扶记录
    @Autowired
    private IFamilyAidLogService familyAidLogService;

    // 3.3.8. 填写贫困户基本信息
    @Autowired
    private IFamilyInfoService familyInfoService;

    // 3.3.9. 填写贫困户收入
    @Autowired
    private IFamilyIncomeService familyIncomeService;

    // 3.3.10. 填写贫困户成员信息
    @Autowired
    private IFamilyMemberService familyMemberService;

    // 系统用户表
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 3.3.1. 贫困户基本信息查询
     * 
     * @param familyId
     * @return
     * @throws BaseAppException
     */
    @RequestMapping("/qryFamilyBaseInfo")
    @ResponseBody
    public ResResult qryFamilyBaseInfo(@RequestParam(value = "familyId",
            required = true) Integer familyId) {
        if (Utils.isEmpty(familyId)) {
            return ResultFactory.getRequestParamsError();
        }
        try {
            ResResult result = new ResResult();
            CodeFamilyInfoPO qryFI = new CodeFamilyInfoPO();
            qryFI.setFamilyId(familyId);
            // 贫困户家庭信息
            List<CodeFamilyInfoPO> familyBaseInfo = codeFamilyInfoService
                    .selectByArg(qryFI);

            if (null == familyBaseInfo || familyBaseInfo.size() == 0) {
                return ResultFactory.getUnableQryData();
            }

            AppFamilyInfoVO rspData = new AppFamilyInfoVO();
            CodeFamilyInfoPO familyInfo = familyBaseInfo.get(0);

            BeanUtils.copyProperties(familyInfo, rspData);
            rspData.setFamilyName(familyInfo.getPersonName());
            rspData.setMemberNum(familyInfo.getTotalMember());
            rspData.setTel(familyInfo.getPersonTel());
            // TODO
            // 贫困属性 povertyState 对应于表里的字段POVERTY_ATTR（贫困户属性）
            // 脱贫属性 shakeOffAttr 对应于表里的字段POVERTY_STATE（贫困状态）
            rspData.setPovertyState(familyInfo.getPovertyAttr());
            rspData.setShakeOffAttr(familyInfo.getPovertyState());
            result.setRspData(rspData);
            return result;
        }
        catch (Exception e) {
            logger.error(e);
            return ResultFactory.getExceptionResult();
        }
    }

    /**
     * 3.3.2. 贫困户成员查询
     * 
     * @param familyId
     * @return
     * @throws BaseAppException
     */
    @RequestMapping("/qryFamilyMembers")
    @ResponseBody
    public ResResult qryFamilyMembers(@RequestParam(value = "familyId",
            required = true) Integer familyId, @RequestParam(value = "page",
            required = true) Integer page, @RequestParam(value = "rows",
            required = true) Integer rows) {
        if (Utils.isEmpty(familyId) || Utils.isEmpty(page)
                || Utils.isEmpty(rows)) {
            return ResultFactory.getRequestParamsError();
        }
        try {
            ResResult result = new ResResult();

            // 家庭成员列表
            CodeFamilyMemberPO qryVO = new CodeFamilyMemberPO();
            qryVO.setFamilyId(familyId);
            Page<CodeFamilyMemberPO> vPage = new Page<CodeFamilyMemberPO>();
            vPage.setPage(page);
            vPage.setRows(rows);
            codeFamilyMemberService.selectByArgAndPage(qryVO, vPage);

            Page<AppFamilyMemberVO> resultPage = new Page<AppFamilyMemberVO>();
            BeanUtils.copyProperties(vPage, resultPage);
            List<CodeFamilyMemberPO> vList = vPage.getResultList();
            List<AppFamilyMemberVO> resultList = new ArrayList<AppFamilyMemberVO>(
                    rows);
            for (CodeFamilyMemberPO vPO : vList) {
                AppFamilyMemberVO rVO = new AppFamilyMemberVO();
                BeanUtils.copyProperties(vPO, rVO);
                rVO.setName(vPO.getPersonName());
                // TODO 设置图片

                resultList.add(rVO);
            }
            resultPage.setResultList(resultList);
            result.setRspData(resultPage);
            return result;
        }
        catch (Exception e) {
            logger.error(e);
            return ResultFactory.getExceptionResult();
        }
    }

    /**
     * 3.3.3. 贫困户走访日志查询
     * 
     * @param familyId
     * @param page
     * @param rows
     * @return
     * @throws BaseAppException
     */
    @ResponseBody
    @RequestMapping("/qryFamilyVisitedLogs")
    public ResResult qryFamilyVisitedLogs(@RequestParam(value = "familyId",
            required = true) Integer familyId, @RequestParam(value = "page",
            required = true) Integer page, @RequestParam(value = "rows",
            required = true) Integer rows) {
        if (Utils.isEmpty(familyId) || Utils.isEmpty(page)
                || Utils.isEmpty(rows)) {
            return ResultFactory.getRequestParamsError();
        }
        try {
            ResResult result = new ResResult();

            // 走访日志
            CodeFamilyVistedLogPO qryVO = new CodeFamilyVistedLogPO();
            qryVO.setFamilyId(familyId);
            Page<CodeFamilyVistedLogPO> vPage = new Page<CodeFamilyVistedLogPO>();
            vPage.setPage(page);
            vPage.setRows(rows);
            codeFamilyVistedLogService.selectByArgAndPage(qryVO, vPage);

            Page<AppFamilyVistedLogVO> resultPage = new Page<AppFamilyVistedLogVO>();
            BeanUtils.copyProperties(vPage, resultPage);
            List<CodeFamilyVistedLogPO> vList = vPage.getResultList();
            List<AppFamilyVistedLogVO> resultList = new ArrayList<AppFamilyVistedLogVO>(
                    rows);
            for (CodeFamilyVistedLogPO vPO : vList) {
                AppFamilyVistedLogVO rVO = new AppFamilyVistedLogVO();
                BeanUtils.copyProperties(vPO, rVO);
                rVO.setFamilyVisitedLog(vPO.getVisitedLogId());

                resultList.add(rVO);
            }
            resultPage.setResultList(resultList);
            result.setRspData(resultPage);
            return result;
        }
        catch (Exception e) {
            logger.error(e);
            return ResultFactory.getExceptionResult();
        }
    }

    /**
     * 3.3.4. 贫困户帮扶记录查询
     * 
     * @param familyId
     * @param page
     * @param rows
     * @return
     * @throws BaseAppException
     */
    @ResponseBody
    @RequestMapping("/qryFamilyAidLogs")
    public ResResult qryFamilyAidLogs(@RequestParam(value = "familyId",
            required = true) Integer familyId, @RequestParam(value = "page",
            required = true) Integer page, @RequestParam(value = "rows",
            required = true) Integer rows) {
        if (Utils.isEmpty(familyId) || Utils.isEmpty(page)
                || Utils.isEmpty(rows)) {
            return ResultFactory.getRequestParamsError();
        }
        try {
            ResResult result = new ResResult();

            CodeFamilyAidLogPO qryVO = new CodeFamilyAidLogPO();
            qryVO.setFamilyId(familyId);
            Page<CodeFamilyAidLogPO> vPage = new Page<CodeFamilyAidLogPO>();
            vPage.setPage(page);
            vPage.setRows(rows);
            codeFamilyAidLogService.selectByArgAndPage(qryVO, vPage);

            Page<AppFamilyAidLogVO> resultPage = new Page<AppFamilyAidLogVO>();
            BeanUtils.copyProperties(vPage, resultPage);
            List<CodeFamilyAidLogPO> vList = vPage.getResultList();
            List<AppFamilyAidLogVO> resultList = new ArrayList<AppFamilyAidLogVO>(
                    rows);
            for (CodeFamilyAidLogPO vPO : vList) {
                AppFamilyAidLogVO rVO = new AppFamilyAidLogVO();
                BeanUtils.copyProperties(vPO, rVO);
                rVO.setAigPhotoList(vPO.getPhotoList());
                resultList.add(rVO);
            }
            resultPage.setResultList(resultList);
            result.setRspData(resultPage);
            return result;
        }
        catch (Exception e) {
            logger.error(e);
            return ResultFactory.getExceptionResult();
        }
    }

    /**
     * 3.3.5. 贫困户收入查询
     * 
     * @param familyId
     * @param page
     * @param rows
     * @return
     * @throws BaseAppException
     */
    @ResponseBody
    @RequestMapping("/qryFamilyIncomes")
    public ResResult qryFamilyIncomes(@RequestParam(value = "familyId",
            required = true) Integer familyId, @RequestParam(value = "page",
            required = true) Integer page, @RequestParam(value = "rows",
            required = true) Integer rows) {
        if (Utils.isEmpty(familyId) || Utils.isEmpty(page)
                || Utils.isEmpty(rows)) {
            return ResultFactory.getRequestParamsError();
        }
        try {
            ResResult result = new ResResult();

            CodeFamilyIncomePO qryVO = new CodeFamilyIncomePO();
            qryVO.setFamilyId(familyId);
            Page<CodeFamilyIncomePO> vPage = new Page<CodeFamilyIncomePO>();
            vPage.setPage(page);
            vPage.setRows(rows);
            codeFamilyIncomeService.selectByArgAndPage(qryVO, vPage);

            Page<AppFamilyIncomeVO> resultPage = new Page<AppFamilyIncomeVO>();
            BeanUtils.copyProperties(vPage, resultPage);
            List<CodeFamilyIncomePO> vList = vPage.getResultList();
            List<AppFamilyIncomeVO> resultList = new ArrayList<AppFamilyIncomeVO>(
                    rows);
            for (CodeFamilyIncomePO vPO : vList) {
                AppFamilyIncomeVO rVO = new AppFamilyIncomeVO();
                BeanUtils.copyProperties(vPO, rVO);

                resultList.add(rVO);
            }
            resultPage.setResultList(resultList);
            result.setRspData(resultPage);
            return result;
        }
        catch (Exception e) {
            logger.error(e);
            return ResultFactory.getExceptionResult();
        }
    }

    /**
     * 3.3.6. 填写走访日志
     * 
     * @param record
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addFamilyVisitedLog", method = RequestMethod.POST)
    public ResResult addFamilyVisitedLog(FamilyVisitedLogPO record) {
        if (Utils.isEmpty(record.getFamilyId())
                || Utils.isEmpty(record.getVisitedDate())
                || Utils.isEmpty(record.getContent())) {
            return ResultFactory.getRequestParamsError();
        }
        ResResult result = new ResResult();
        try {
            int pkId = familyVisitedLogService.add(record);
            result.setRspData(pkId);
        }
        catch (Exception e) {
            logger.error(e);
            return ResultFactory.getExceptionResult();
        }
        return result;
    }

    /**
     * 3.3.7. 填写帮扶记录
     * 
     * @param record
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addFamilyAidLog", method = RequestMethod.POST)
    public ResResult addFamilyAidLog(FamilyAidLogPO record) {
        if (Utils.isEmpty(record.getFamilyId())
                || Utils.isEmpty(record.getAidDate())
                || Utils.isEmpty(record.getAidDesc())
                || Utils.isEmpty(record.getProjectId())
                || Utils.isEmpty(record.getPhotoList())
                || Utils.isEmpty(record.getAidAmount())) {
            return ResultFactory.getRequestParamsError();
        }
        ResResult result = new ResResult();
        try {
            int pkId = familyAidLogService.add(record);
            result.setRspData(pkId);
        }
        catch (Exception e) {
            logger.error(e);
            return ResultFactory.getExceptionResult();
        }
        return result;
    }

    /**
     * 3.3.8. 填写贫困户基本信息
     * 
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addFamilyBaseInfo", method = RequestMethod.POST)
    public ResResult addFamilyBaseInfo(AppFamilyInfoPO inputPO) {
        if (Utils.isEmpty(inputPO.getFamilyId())
                || Utils.isEmpty(inputPO.getIsDropOut())
                || Utils.isEmpty(inputPO.getIsDangerous())
                || Utils.isEmpty(inputPO.getIsNrcms())
                || Utils.isEmpty(inputPO.getIsEndowment())
                || Utils.isEmpty(inputPO.getMainReason())
                || Utils.isEmpty(inputPO.getPovertyState())
                || Utils.isEmpty(inputPO.getShakeOffAttr())
                || Utils.isEmpty(inputPO.getReason())
                || Utils.isEmpty(inputPO.getPlanShakeOffDate())) {
            return ResultFactory.getRequestParamsError();
        }
        ResResult result = new ResResult();
        try {
            FamilyInfoPO rPO = new FamilyInfoPO();
            BeanUtils.copyProperties(inputPO, rPO);
            rPO.setPovertyAttr(inputPO.getPovertyState());
            rPO.setPovertyState(inputPO.getShakeOffAttr());
            int pkId = familyInfoService.update(rPO);
            result.setRspData(pkId);
        }
        catch (Exception e) {
            logger.error(e);
            return ResultFactory.getExceptionResult();
        }
        return result;
    }

    /**
     * 3.3.9. 填写贫困户收入
     * 
     * @param record
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addFamilyIncome", method = RequestMethod.POST)
    public ResResult addFamilyIncome(FamilyIncomePO record) {
        if (Utils.isEmpty(record.getFamilyId())
                || Utils.isEmpty(record.getStatDate())
                || Utils.isEmpty(record.getStatQuarter())
                || Utils.isEmpty(record.getAllAmount())
                || Utils.isEmpty(record.getAvgAmount())
                || Utils.isEmpty(record.getWorkAmount())
                || Utils.isEmpty(record.getEconAmount())
                || Utils.isEmpty(record.getPropertyAmount())
                || Utils.isEmpty(record.getSubsidyAmount())
                || Utils.isEmpty(record.getAidAmount())
                || Utils.isEmpty(record.getEconPayout())
                || Utils.isEmpty(record.getMedicalPayout())
                || Utils.isEmpty(record.getPropertyPayout())) {
            return ResultFactory.getRequestParamsError();
        }

        ResResult result = new ResResult();
        try {
            FamilyIncomePO qryFI = new FamilyIncomePO();
            qryFI.setFamilyId(record.getFamilyId());
            qryFI.setStatDate(record.getStatDate());
            qryFI.setStatQuarter(record.getStatQuarter());
            List<FamilyIncomePO> existFIList = familyIncomeService.selectByArg(qryFI);
            if(null != existFIList && existFIList.size()>0){
                return ResultFactory.getExistDataException(); 
            }
            int pkId = familyIncomeService.add(record);
            result.setRspData(pkId);
        }
        catch (Exception e) {
            logger.error(e);
            return ResultFactory.getExceptionResult();
        }
        return result;
    }

    /**
     * 3.3.10. 填写贫困户成员信息
     * 
     * @param record
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addFamilyMember", method = RequestMethod.POST)
    @Deprecated
    public ResResult addFamilyMember(FamilyMemberPO record) {
        ResResult result = new ResResult();
        try {
            int pkId = familyMemberService.add(record);
            result.setRspData(pkId);
        }
        catch (Exception e) {
            logger.error(e);
            return ResultFactory.getExceptionResult();
        }
        return result;
    }

    /**
     * 3.3.11. 采集家庭照片
     * 
     * @param familyId
     * @param photoList
     * @param updateType
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateFamilyPhotoList",
            method = RequestMethod.POST)
    public ResResult updateFamilyPhotoList(
            @RequestParam(value = "familyId", required = true) Integer familyId,
            @RequestParam(value = "photoList", required = true) String photoList,
            @RequestParam(value = "updateType", required = true) Integer updateType) {
        if (Utils.isEmpty(familyId) || Utils.isEmpty(photoList)
                || Utils.isEmpty(updateType)
                || (updateType < 0 || updateType > 1)) {
            return ResultFactory.getRequestParamsError();
        }
        ResResult result = new ResResult();
        try {
            FamilyInfoPO rPO = new FamilyInfoPO();
            rPO.setFamilyId(familyId);
            if (0 == updateType) {
                // 追加
                FamilyInfoPO exist = familyInfoService
                        .selectByPrimaryKey(familyId);
                if (Utils.notEmpty(exist.getPhotoList())) {
                    photoList = exist.getPhotoList() + "," + photoList;
                }
            }
            rPO.setPhotoList(photoList);
            int pkId = familyInfoService.update(rPO);
            result.setRspData(pkId);
        }
        catch (Exception e) {
            logger.error(e);
            return ResultFactory.getExceptionResult();
        }
        return result;
    }

    /**
     * 3.3.12. 采集成员照片
     * 
     * @param familyMemeberId
     * @param personPhoto
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateFamilyMemberPhoto",
            method = RequestMethod.POST)
    public ResResult updateFamilyMemberPhoto(
            @RequestParam(value = "familyMemeberId", required = true) Integer familyMemeberId,
            @RequestParam(value = "familyPhoto", required = true) String personPhoto) {
        if (Utils.isEmpty(familyMemeberId) || Utils.isEmpty(personPhoto)) {
            return ResultFactory.getRequestParamsError();
        }
        ResResult result = new ResResult();
        try {
            FamilyMemberPO record = new FamilyMemberPO();
            record.setFamilyMemeberId(familyMemeberId);
            record.setPersonPhoto(personPhoto);
            int pkId = familyMemberService.update(record);
            result.setRspData(pkId);

            // 更新照片到系统用户表中
            try {
                FamilyMemberPO existRecord = familyMemberService
                        .selectByPrimaryKey(familyMemeberId);
                String tel = existRecord.getTel();
                SysUserPO qryRecord = new SysUserPO();
                qryRecord.setLoginName(tel);
                List<SysUserPO> userList = sysUserService
                        .selectByArg(qryRecord);

                if (null != userList && userList.size() > 0) {
                    SysUserPO userRecord = new SysUserPO();
                    userRecord.setUserId(userList.get(0).getUserId());
                    userRecord.setLoginName(tel);
                    userRecord.setHeadImgUrl(personPhoto);
                    sysUserService.update(userRecord);
                }

            }
            catch (Exception e) {
                logger.error(e);
            }
        }
        catch (Exception e) {
            logger.error(e);
            return ResultFactory.getExceptionResult();
        }
        return result;
    }

}
